package icu.cocoon.system.runner;

import icu.cocoon.system.entity.Org;
import icu.cocoon.system.entity.User;
import icu.cocoon.system.service.OrgService;
import icu.cocoon.system.service.UserService;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
@Slf4j
public class AfterRunner implements CommandLineRunner {

  @Resource
  private UserService userService;

  @Resource
  private OrgService orgService;

  @Resource
  private RedisTemplate<String,Object> redisTemplate;

  @Override
  public void run(String... args) {
    cleanAllCache();
    List<Org> orgList = orgService.findByName("超管组织");
    if (CollectionUtils.isEmpty(orgList)){
      Org org = new Org();
      org.setName("超管组织");
      org.setParentId(0L);
      orgService.create(org);
      orgList.add(org);
    }


    User user = userService.getByUsername("admin");
    if (user == null) {
      log.error("不存在超级管理员，创建中");
      user = new User();
      user.setName("超级管理员");
      user.setUsername("admin");
      user.setPassword("admin");
      user.setPhone("19999999999");
      user.setOrgId(orgList.get(0).getId());
      userService.create(user);
      log.info("创建成功");
    }
    log.warn("SpringBoot 已经启动");
  }


  private void cleanAllCache(){
    Set<String> keys = redisTemplate.keys("*");
    if (CollectionUtils.isEmpty(keys)){
      return;
    }
    keys.forEach(k->redisTemplate.delete(k));
    log.warn("已清空缓存");
  }
}
